package com.xiaobai.netease_news.activities;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.tencent.qq.QQ;

import com.xiaobai.netease_news.R;
import com.xiaobai.netease_news.adapters.MyAdapter;

import java.util.HashMap;

public class LoginActivity extends FragmentActivity
        implements View.OnClickListener, Handler.Callback, PlatformActionListener {

    private static final int MSG_SMSSDK_CALLBACK = 1;
    private static final int MSG_AUTH_CANCEL = 2;
    private static final int MSG_AUTH_ERROR = 3;
    private static final int MSG_AUTH_COMPLETE = 4;

    private Handler handler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ShareSDK.initSDK(this);
        handler = new Handler(this);
        ImageView fanhuiwode = (ImageView) findViewById(R.id.fanhuiwode);
        TextView xinlangdenglu = (TextView) findViewById(R.id.xinlangweibodenglu);
        TextView qqdenglu = (TextView) findViewById(R.id.qqdenglu);
        Button yijianfenxiang = (Button) findViewById(R.id.yijianfenxiang);
        Button tengxunweibodenglu = (Button) findViewById(R.id.tengxunweibodenglu);
        tengxunweibodenglu.setOnClickListener(this);
        yijianfenxiang.setOnClickListener(this);
        fanhuiwode.setOnClickListener(this);
        xinlangdenglu.setOnClickListener(this);
        qqdenglu.setOnClickListener(this);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_login, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id) {
            case R.id.fanhuiwode:
                finish();
                break;
            case R.id.xinlangweibodenglu:
                //新浪微博
                Platform sina = ShareSDK.getPlatform(SinaWeibo.NAME);

                sina.followFriend(MyAdapter.SDK_SINAWEIBO_UID);
//                sina.SSOSetting(false);
                sina.SSOSetting(true);
                sina.setPlatformActionListener(this);
                sina.authorize();
                sina.showUser(null);
                break;
            case R.id.tengxunweibodenglu:
                Platform tengxunweibo = ShareSDK.getPlatform("TencentWeibo");
                tengxunweibo.followFriend(MyAdapter.SDK_TENCENTWEIBO_UID);
                tengxunweibo.SSOSetting(false);
                tengxunweibo.setPlatformActionListener(this);
                tengxunweibo.authorize();
                tengxunweibo.showUser(null);
                break;
            case R.id.qqdenglu:
                Platform qq = ShareSDK.getPlatform(QQ.NAME);
                qq.SSOSetting(false);
                qq.setPlatformActionListener(this);
                qq.authorize();
                qq.showUser(null);
                break;
            case R.id.yijianfenxiang:
                OnekeyShare oks = new OnekeyShare();
//                oks.setSilent(true);   隐藏编辑页面
//                oks.setSilent(false); 显示编辑页面
                //关闭sso授权
                oks.disableSSOWhenAuthorize();

                // 分享时Notification的图标和文字  2.5.9以后的版本不调用此方法
                //oks.setNotification(R.drawable.ic_launcher, getString(R.string.app_name));
                // title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间使用
                oks.setTitle("分享");
                // titleUrl是标题的网络链接，仅在人人网和QQ空间使用
                oks.setTitleUrl("http://sharesdk.cn");
                // text是分享文本，所有平台都需要这个字段
                oks.setText("小白十番队内测:ShareSDK for Android不仅集成简单、支持如QQ好友、微信、新浪微博、腾讯微博等所有社交平台，而且还有强大的统计分析管理后台，实时了解用户、信息流、回流率、传播效应等数据，详情见官网http://mob.com @ShareSDK");
                // imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
//                oks.setImagePath("/sdcard/test.jpg");//确保SDcard下面存在此张图片
                oks.setImagePath("http://img2.imgtn.bdimg.com/it/u=2710221228,3951408912&fm=23&gp=0.jpg");
                // url仅在微信（包括好友和朋友圈）中使用
                oks.setUrl("http://sharesdk.cn");
                // comment是我对这条分享的评论，仅在人人网和QQ空间使用
                oks.setComment("我是测试评论文本");
                // site是分享此内容的网站名称，仅在QQ空间使用
                oks.setSite(getString(R.string.app_name));
                // siteUrl是分享此内容的网站地址，仅在QQ空间使用
                oks.setSiteUrl("http://sharesdk.cn");

                oks.setSilent(false);
                oks.setDialogMode();

                // 启动分享GUI
                oks.show(this);
                break;
        }
    }

    @Override
    public void onComplete(Platform platform, int action, HashMap<String, Object> res) {
//
        if (action == Platform.ACTION_USER_INFOR) {
            Message msg = new Message();
            msg.what = MSG_AUTH_COMPLETE;
            msg.obj = new Object[]{platform.getName(), res};
            handler.sendMessage(msg);
        }
    }

    @Override
    public void onError(Platform platform, int action, Throwable throwable) {
        if (action == Platform.ACTION_USER_INFOR) {
            handler.sendEmptyMessage(MSG_AUTH_ERROR);
        }
        throwable.printStackTrace();
    }

    @Override
    public void onCancel(Platform platform, int action) {
        if (action == Platform.ACTION_USER_INFOR)
            handler.sendEmptyMessage(MSG_AUTH_CANCEL);
    }

    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            case MSG_AUTH_CANCEL:
                //取消授权
                Toast.makeText(this, "授权操作已取消", Toast.LENGTH_SHORT).show();
                break;
            case MSG_AUTH_ERROR:
                //授权失败
                Toast.makeText(this, "授权操作遇到错误，请阅读Logcat输出;如微信登录，需要微信客户端", Toast.LENGTH_SHORT).show();
                break;
            case MSG_AUTH_COMPLETE:
                //授权成功
                Toast.makeText(this, "授权成功，正在跳转登录操作…", Toast.LENGTH_SHORT).show();
                Object[] objs = (Object[]) msg.obj;
                String platform = (String) objs[0];
                Log.d("----->", "platform:" + platform);
                HashMap<String, Object> res = (HashMap<String, Object>) objs[1];
                Bundle bundle = new Bundle();
                bundle.putString("platform", platform);
                for (String key : res.keySet()) {
                    String value = res.get(key).toString();
                    Log.d("----->", "key=" + key + ",value=" + value);
                    bundle.putString(key, value);
                }
                Intent intent = new Intent();
                intent.putExtras(bundle);
                setResult(444, intent);
                finish();
                break;
        }
        return false;
    }
}
